<script setup>
import {ref, defineEmits, defineProps} from "vue"
import {
  insertAssignment, insertAssignmentQuestionOptions,
  insertAssignmentQuestions, insertClassPractice, insertClassPracticeOptions,
  insertDiscussion, insertQuestionnaireQuestionOptions, insertQuestionnaireQuestions,
  insertTask
} from "../../../../api/course/course.js";
import {ElMessage} from "element-plus";
import router from "../../../../router/index.js";


const emit = defineEmits(['close']);
const props = defineProps(['isInsertTask', 'practices', 'type', 'data']);
// 是否添加任务
const isInsertTask = ref(false)
// 任务信息
const task = ref({
  id: 0,
  courseId:0,
  name: '',
  type: '',
  startTime: '',
  endTime: ''
})


isInsertTask.value = props.isInsertTask;

// 选择任务类型
const handleChooseTask = async () => {
  task.value.type = props.type;
  if (props.type === 0) {
    handleInsertSignIn();
  } else if (props.type === 1) {
    handleClassPractice();
  } else if (props.type === 2) {
    await handleInsertTopicDiscuss()
  } else if (props.type === 3) {
    handleInsertQuestionnaire();
  }
}

// 添加签到
const handleInsertSignIn = () => {

}

// 添加随堂练习
const handleClassPractice = () => {
  console.log(props.practices);
  task.value.courseId = localStorage.getItem('courseId');
  console.log(task.value);
  // 判断作业题目和答案是否为空
  for (let i = 0; i < props.practices.length; i++) {
    for (let j = 0; j < props.practices[i].content.length; j++) {
      if (props.practices[i].content[j].content == '') {
        ElMessage.error('有题目为空,无法上传');
        return;
      }
      if (props.practices[i].content[j].answer == '') {
        ElMessage.error('有答案为空,无法上传');
        return;
      }
    }
  }
  //   上传作业信息
  const newContentArray = props.practices.flatMap(item =>
      item.content.map(({answer, content, id, type}) => ({answer, content, id, type}))
  );
  // 作业选项信息解析
  const optionsArray = props.practices.flatMap(item =>
      item.content
          .filter(obj => obj.option)  // 过滤掉没有 option 字段的对象
          .map(({option}) => option)  // 提取 option 字段
  );
  console.log(optionsArray);
  console.log(newContentArray);
  // 上传作业题目
  console.log(task.value);
  insertTask(task.value).then(res => {
    task.value.id = res.data;
    //   上传作业题目
    insertClassPractice(task.value.id, newContentArray).then(res => {
      const ids = res.data;
      console.log(ids);
      for (let i = 0; i < ids.length; i++) {
        optionsArray[i].taskQuestionId = ids[i];
      }
      console.log(optionsArray);
      insertClassPracticeOptions(optionsArray).then(res => {
        emit('close');
        ElMessage.success('随堂练习上传成功');
        router.push("/course/classmanage/task");
      });
    })
  })
}

// 添加主题讨论
const handleInsertTopicDiscuss = async () => {
  task.value.courseId = localStorage.getItem('courseId');
  await insertTask(task.value).then(res => {
    console.log(res.data);
    props.data.taskId = res.data;
    console.log(props.data);
    insertDiscussion(props.data).then(() => {
      ElMessage.success("创建主题讨论成功");
      router.push("/course/classmanage/task");
    })
  })
}

// 添加问卷
const handleInsertQuestionnaire = () => {
  console.log(props.practices);
  task.value.courseId = localStorage.getItem('courseId');
  console.log(task.value);
  // 判断作业题目和答案是否为空
  for (let i = 0; i < props.practices.length; i++) {
    for (let j = 0; j < props.practices[i].content.length; j++) {
      if (props.practices[i].content[j].content == '') {
        ElMessage.error('有题目为空,无法上传');
        return;
      }
    }
  }
  //   上传作业信息
  const newContentArray = props.practices.flatMap(item =>
      item.content.map(({answer, content, id, type}) => ({answer, content, id, type}))
  );
  // 作业选项信息解析
  const optionsArray = props.practices.flatMap(item =>
      item.content
          .filter(obj => obj.option)  // 过滤掉没有 option 字段的对象
          .map(({option}) => option)  // 提取 option 字段
  );
  console.log(optionsArray);
  console.log(newContentArray);
  // 上传作业题目
  console.log(task.value);
  insertTask(task.value).then(res => {
    task.value.id = res.data;
    //   上传作业题目
    insertQuestionnaireQuestions(task.value.id, newContentArray).then(res => {
      const ids = res.data;
      console.log(ids);
      for (let i = 0; i < ids.length; i++) {
        optionsArray[i].taskQuestionnaireId = ids[i];
      }
      console.log(optionsArray);
      insertQuestionnaireQuestionOptions(optionsArray).then(res => {
        emit('close');
        ElMessage.success('问卷上传成功');
        router.push("/course/classmanage/task");
      });
    })
  })
}

</script>

<template>
  <el-dialog
      v-model="isInsertTask"
      title="填写任务信息"
      width="500"
      align-center
  >
    <el-form
        :label-position="'left'"
        label-width="auto"
        :model="task"
        style="max-width: 600px"
    >
      <el-form-item label="任务名称">
        <el-input v-model="task.name" placeholder="请输入任务名称"/>
      </el-form-item>

      <div class="demo-time-range">
        <el-form-item label="任务开始时间">
          <el-date-picker
              v-model="task.startTime"
              type="datetime"
              placeholder="开始时间"
          />
        </el-form-item>
        <el-form-item label="任务结束时间">
          <el-date-picker
              v-model="task.endTime"
              type="datetime"
              placeholder="结束时间"
          />
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="emit('close')">取消</el-button>
        <el-button type="primary" @click="handleChooseTask">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="less">

</style>